<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>结算</title>
    <style>
        /* 结算页面样式 */
        body {
            margin: 0;
            padding: 0;
            font-family: "PingFang SC", "Microsoft YaHei", sans-serif;
            background-color: #f5f7fa;
            color: #333;
        }

        .checkout-container {
            background-color: white;
            width: 100%;
            max-height: 100vh;
            overflow-y: auto;
            padding: 20px;
        }

        .checkout-header {
            font-size: 24px;
            font-weight: 500;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 1px solid #eee;
        }

        .checkout-section {
            margin-bottom: 30px;
            background: #fff;
            border-radius: 4px;
            padding: 20px;
        }

        .section-title {
            font-size: 18px;
            font-weight: 500;
            margin-bottom: 20px;
            color: #333;
            display: flex;
            align-items: center;
        }

        .section-title i {
            margin-right: 10px;
            color: #409EFF;
        }

        .address-item {
            padding: 15px;
            border: 1px solid #e0e0e0;
            border-radius: 4px;
            margin-bottom: 10px;
            cursor: pointer;
            transition: all 0.3s;
        }

        .address-item:hover {
            border-color: #409EFF;
        }

        .address-item.selected {
            border-color: #409EFF;
            background-color: #f0f7ff;
        }

        .address-detail {
            margin-top: 5px;
            color: #666;
            line-height: 1.6;
        }

        .receiver {
            font-weight: bold;
            margin-right: 10px;
        }

        .default-tag {
            display: inline-block;
            background-color: #409EFF;
            color: white;
            padding: 2px 5px;
            font-size: 12px;
            border-radius: 2px;
            margin-right: 5px;
        }

        .product-table {
            width: 100%;
            border-collapse: collapse;
        }

        .product-table th {
            background-color: #f5f7fa;
            padding: 12px 10px;
            text-align: left;
            font-weight: 500;
            color: #909399;
        }

        .product-table td {
            padding: 12px 10px;
            border-bottom: 1px solid #ebeef5;
        }

        .product-image {
            width: 60px;
            height: 60px;
            border-radius: 4px;
            object-fit: cover;
        }

        .product-name {
            margin-left: 10px;
            color: #606266;
        }

        .product-price {
            color: #f56c6c;
            font-weight: bold;
        }

        .summary-row {
            display: flex;
            justify-content: flex-end;
            margin-top: 20px;
            padding-top: 20px;
            border-top: 1px solid #ebeef5;
        }

        .summary-item {
            margin-left: 30px;
            text-align: right;
        }

        .summary-label {
            color: #909399;
            margin-bottom: 5px;
        }

        .summary-value {
            font-size: 18px;
            color: #f56c6c;
            font-weight: bold;
        }

        .submit-btn {
            margin-top: 30px;
            text-align: right;
        }

        .company-info {
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid #eee;
        }

        .company-name {
            font-weight: bold;
            margin-bottom: 5px;
        }

        .company-address {
            color: #666;
            font-size: 14px;
        }
    </style>
</head>
<body>
<div id="app">
    <div class="checkout-container">
        <div class="checkout-header">填写并核对订单信息</div>

        <!-- 公司信息 -->
        <div class="company-info">
            <div class="company-name">公司</div>
            <div class="company-address">中国安徽省马鞍山市当涂县石桥镇大转盘马鞍山宏运缝纫设备贸易有限公司</div>
        </div>

        <!-- 收货地址部分 -->
        <div class="checkout-section">
            <div class="section-title">
                <i class="el-icon-location-outline"></i>
                <span>收货地址</span>
            </div>

            <el-radio-group v-model="selectedAddress">
                <div class="address-item" v-for="(address, index) in addresses" :key="address.addressId"
                     :class="{selected: selectedAddress === index}">
                    <el-radio :label="index">
                        <span v-if="address.isDefault === 1" class="default-tag">默认</span>
                        <span class="receiver">{{address.receiverName}}</span>
                        <span>{{address.phone}}</span>
                        <div class="address-detail">
                            {{address.province || ''}}{{address.city || ''}}{{address.district || ''}}{{address.detailAddress}}
                        </div>
                    </el-radio>
                </div>
            </el-radio-group>

            <el-button type="text" icon="el-icon-plus" @click="goToAddress">新增收货地址</el-button>
        </div>

        <!-- 配送方式部分 -->
        <div class="checkout-section">
            <div class="section-title">
                <i class="el-icon-truck"></i>
                <span>配送方式</span>
            </div>

            <el-form label-width="100px">
                <el-form-item label="物流方式：">
                    <el-select v-model="shippingMethod" placeholder="请选择物流方式" style="width: 300px;">
                        <el-option label="快递配送" value="delivery"></el-option>
                        <el-option label="自提" value="self_pickup"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="备注：">
                    <el-input
                            type="textarea"
                            :rows="3"
                            placeholder="请填写备注"
                            v-model="remark"
                            style="width: 300px;">
                    </el-input>
                </el-form-item>
            </el-form>
        </div>

        <!-- 商品列表部分 -->
        <div class="checkout-section">
            <div class="section-title">
                <i class="el-icon-shopping-cart-2"></i>
                <span>商品列表</span>
            </div>

            <table class="product-table">
                <thead>
                <tr>
                    <th>序号</th>
                    <th>商品</th>
                    <th>单价</th>
                    <th>数量</th>
                    <th>小计</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody>
                <tr v-for="(item, index) in selectedItems" :key="item.id">
                    <td>{{index + 1}}</td>
                    <td>
                        <div style="display: flex; align-items: center;">
                            <img :src="item.imageUrl" class="product-image">
                            <span class="product-name">{{item.productName}}</span>
                        </div>
                    </td>
                    <td class="product-price">¥{{item.price.toFixed(2)}}</td>
                    <td>{{item.quantity}}</td>
                    <td class="product-price">¥{{(item.price * item.quantity).toFixed(2)}}</td>
                    <td>
                        <el-button type="text" @click="removeFromCheckout(index)">删除</el-button>
                    </td>
                </tr>
                </tbody>
            </table>

            <div class="summary-row">
                <div class="summary-item">
                    <div class="summary-label">商品件数</div>
                    <div class="summary-value">{{totalQuantity}}件</div>
                </div>
                <div class="summary-item">
                    <div class="summary-label">商品总重量</div>
                    <div class="summary-value">{{totalWeight}}KG</div>
                </div>
                <div class="summary-item">
                    <div class="summary-label">合计（不含运费）</div>
                    <div class="summary-value">¥{{subTotal.toFixed(2)}}</div>
                </div>
                <div class="summary-item">
                    <div class="summary-label">实付款</div>
                    <div class="summary-value">¥{{totalAmount.toFixed(2)}}</div>
                </div>
            </div>
        </div>

        <div class="submit-btn">
            <el-button @click="closeCheckoutModal">取消</el-button>
            <el-button type="primary" @click="submitOrder">提交订单</el-button>
        </div>
    </div>
</div>

<script src="../js/axios-0.18.0.js"></script>
<script src="../js/vue.js"></script>
<script src="../js/element-ui/lib/index.js"></script>
<link rel="stylesheet" href="../js/element-ui/lib/theme-chalk/index.css">
<script>
    new Vue({
        el: '#app',
        data() {
            return {
                selectedAddress: 0,
                shippingMethod: '',
                remark: '',
                userId: 1,
                addresses: [],
                selectedItems: []
            }
        },
        created() {
            // 从父窗口获取数据
            window.addEventListener('message', (event) => {
                if (event.data.type === 'initCheckout') {
                    this.userId = event.data.userId;
                    this.selectedItems = event.data.selectedItems;
                    this.getUserAddress();
                }
            });
        },
        computed: {
            totalQuantity() {
                return this.selectedItems.reduce((total, item) => total + item.quantity, 0);
            },
            totalWeight() {
                return this.selectedItems.reduce((total, item) => total + (item.weight * item.quantity), 0).toFixed(2);
            },
            subTotal() {
                return this.selectedItems.reduce((total, item) => total + (item.price * item.quantity), 0);
            },
            totalAmount() {
                return this.subTotal;
            }
        },
        methods: {
            getUserAddress() {
                axios({
                    method: 'get',
                    url: '/user/getUserAddress',
                    params: { userId: this.userId }
                }).then(resp => {
                    this.addresses = Array.isArray(resp.data.data) ? resp.data.data : [];
                    if (this.addresses.length > 0) {
                        const defaultIndex = this.addresses.findIndex(addr => addr.isDefault === 1);
                        this.selectedAddress = defaultIndex !== -1 ? defaultIndex : 0;
                    }
                }).catch(error => {
                    this.$message.error('获取地址失败');
                    console.error('获取地址失败', error);
                    this.addresses = [];
                });
            },
            removeFromCheckout(index) {
                // 通知父窗口删除商品
                window.parent.postMessage({
                    type: 'removeFromCheckout',
                    cartId: this.selectedItems[index].cartId
                }, '*');

                this.selectedItems.splice(index, 1);
                this.$message.success('已从购物车移除商品');
            },
            goToAddress() {
                window.parent.postMessage({
                    type: 'changePage',
                    url: 'address.html'
                }, '*');
            },
            closeCheckoutModal() {
                window.parent.postMessage({
                    type: 'closeCheckout'
                }, '*');
            },
            async submitOrder() {
                // 验证必填项
                if (!this.shippingMethod) {
                    this.$message.warning('请选择物流方式');
                    return;
                }

                if (this.addresses.length === 0) {
                    this.$message.warning('请添加收货地址');
                    return;
                }

                // 检查是否有选中的商品
                if (this.selectedItems.length === 0) {
                    this.$message.warning('请选择要结算的商品');
                    return;
                }

                // 准备订单数据
                const orderData = {
                    userId: this.userId,
                    remark: this.remark,
                    status: 'pending_payment',
                    shippingAddressId: this.addresses[this.selectedAddress].addressId,
                    totalAmount: this.totalAmount,
                    shippingMethod: this.shippingMethod,
                    paymentMethod: 'bank_transfer',
                    orderItems: this.selectedItems.map(item => ({
                        productId: item.productId,
                        quantity: item.quantity,
                        price: item.price
                    }))
                };

                const cartIdsToDelete = this.selectedItems.map(item => item.cartId);

                const loadingInstance = this.$loading({
                    lock: true,
                    text: '订单提交中...',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.7)'
                });

                try {
                    const orderResponse = await axios({
                        method: 'post',
                        url: '/user/insertOrder',
                        data: orderData
                    });

                    if (orderResponse.data.code !== 20011) {
                        throw new Error(orderResponse.data.msg || '订单提交失败');
                    }

                    // 通知父窗口订单创建成功
                    window.parent.postMessage({
                        type: 'orderCreated',
                        orderId: orderResponse.data.data.orderId,
                        cartIds: cartIdsToDelete
                    }, '*');

                    this.$message.success('订单创建成功！');

                } catch (error) {
                    console.error('订单处理失败:', error);
                    const errorMsg = error.response?.data?.msg || error.message || '订单提交失败';
                    this.$message.error(errorMsg);
                } finally {
                    loadingInstance.close();
                }
            }
        }
    });
</script>
</body>
</html>